package com.bobo.netty.server.echo;

import com.bobo.netty.common.Constants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class EchoServer {
    private NioEventLoopGroup nioEventLoopGroup ;
    private ServerBootstrap serverBootstrap;

    public void open() throws InterruptedException {
        serverBootstrap = new ServerBootstrap();
        nioEventLoopGroup = new NioEventLoopGroup();
        serverBootstrap.option(ChannelOption.SO_BACKLOG,128)
                .group(nioEventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoServerHandler());

                    }
                });
        ChannelFuture sync = serverBootstrap.bind(Constants.ECHO_PORT).sync();
        sync.channel().closeFuture().sync();
    }

    public static void main(String[] args) throws InterruptedException {
        EchoServer echoServer = new EchoServer();
        echoServer.open();
    }

}
